package cn.lili.modules.goods.entity.dto;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.db.sql.SqlFormatter;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.goods.entity.enums.GoodsAuthEnum;
import cn.lili.modules.goods.entity.enums.GoodsMarketEnum;
import cn.lili.modules.goods.entity.enums.GoodsTypeEnum;
import cn.lili.modules.goods.entity.enums.SalesModeEnum;
import cn.lili.modules.system.constants.DictConstant;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Date;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 商品查询条件
 *
 * @author pikachu
 * @since 2020-02-24 19:27:20
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class GoodsSearchParams extends PageVO {

    private static final long serialVersionUID = 2544015852728566887L;

    @ApiModelProperty(value = "商品编号")
    private String goodsId;

    @ApiModelProperty(value = "商品编号")
    private String templateId;

    @ApiModelProperty(value = "商品名称")
    private String goodsName;

    @ApiModelProperty(value = "供应商名称")
    private String supplierName;

    @ApiModelProperty(value = "商品名称")
    private String eqGoodsName;

    @ApiModelProperty(value = "商品编号")
    private String id;

    @ApiModelProperty(value = "不等于商品编号")
    private String neId;

    @ApiModelProperty(value = "商品编号")
    private List<String> ids;

    @ApiModelProperty(value = "商品编号")
    private List<String> goodsIds;

    @ApiModelProperty(value = "商家ID")
    private String storeId;

    @ApiModelProperty(value = "卖家名字")
    private String storeName;

    @ApiModelProperty(value = "价格,可以为范围，如10_1000")
    private String price;

    @ApiModelProperty(value = "分类path")
    private String categoryPath;

    @ApiModelProperty(value = "店铺分类id")
    private String storeCategoryPath;

    @ApiModelProperty(value = "是否自营")
    private Boolean selfOperated;

    /**
     * @see GoodsMarketEnum
     */
    @ApiModelProperty(value = "上下架状态")
    private String marketEnable;

    /**
     * @see GoodsAuthEnum
     */
    @ApiModelProperty(value = "审核状态")
    private String authFlag;

    @ApiModelProperty(value = "库存数量")
    private Integer leQuantity;

    @ApiModelProperty(value = "库存数量")
    private Integer geQuantity;

    @ApiModelProperty(value = "是否为推荐商品")
    private Boolean recommend;

    /**
     * @see cn.lili.modules.goods.entity.enums.GoodsTypeEnum
     */
    @ApiModelProperty(value = "商品类型")
    private String goodsType;

    @ApiModelProperty(value = "支持代发")
    private Boolean supportProxy;

    @ApiModelProperty(value = "支持采购")
    private Boolean supportPurchase;

    @ApiModelProperty(value = "代理商品")
    private Boolean isProxyGoods;

    @ApiModelProperty(value = "场景")
    private String scene;

    /**
     * @see SalesModeEnum
     */
    @ApiModelProperty(value = "销售模式", required = true)
    private String salesModel;

    @ApiModelProperty(value = "删除标识")
    private Boolean deleteFlag;

    @ApiModelProperty(value = "供应商ID")
    private String supplierId;

    @ApiModelProperty(value = "等于店铺和供应商ID")
    private String storeAndSupplierId;

    @ApiModelProperty(value = "是否绿色商品")
    private Boolean isGreenGoods;

    @ApiModelProperty(value = "是否新品")
    private Boolean isNew;

    @ApiModelProperty(value = "店铺分类")
    private String selectName;

    @ApiModelProperty(value = "游标")
    private Integer cursor;

    @ApiModelProperty(value = "是否会员商品")
    private Boolean isVipGoods;

    @ApiModelProperty(value = "是否会员商品")
    private Boolean isCommonwealGoods;

    @ApiModelProperty(value = "城市站点id和商家id，逗号分隔")
    private String urbanIdAndStoreId;

    @ApiModelProperty(value = "场景类型：0全返商品查询")
    private Integer sceneType;
    @ApiModelProperty(value = "授权空间ID")
    private String authSpaceId;

    @ApiModelProperty(value = "需要去除的ID")
    List<String> notGoodsIds;


    @ApiModelProperty(value = "盲盒规则ID")
    private String mhId;

    @ApiModelProperty(value = "标签名")
    private Integer goodsTag;

    @ApiModelProperty(value = "标签名")
    private String goodsTagList;

    @ApiModelProperty(value = "发布状态")
    private Integer publishType;

    @ApiModelProperty(value = "排除已选择的商品")
    private String mhNotId;

    /**
     * 开始时间
     */
    private String startCreateTime;

    /**
     * 结束时间
     */
    private String endCreateTime;

    /**
     * 盲盒ID
     */
    private String name;
    /**
     * 是否盲盒商品
     */
    private Boolean isMh;

    /**
     * 店铺id
     */
    private String extendId;
    /**
     * 礼包类型名称
     */
    private String packName;
    /**
     * 礼包类型编号
     */
    private String packNo;

    /**
     * 礼包id
     */
    private String packId;


    /**
     * 查询免税精品: 1,热销商品 2,新品商品
     */
    private Integer queryType;

    public GoodsSearchParams(Integer pageNumber, Integer pageSize) {
        this.setPageNumber(pageNumber);
        this.setPageSize(pageSize);
    }

    public <T> QueryWrapper<T> queryWrapper() {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (CharSequenceUtil.isNotEmpty(id)) {
            List<String> idList = Arrays.asList(id.split(","));
            if (idList.size() > 1) {
                queryWrapper.in("id", idList);
            } else {
                queryWrapper.like("id", id);
            }
        }
        queryWrapper.ne(CharSequenceUtil.isNotEmpty(neId), "id", neId);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(goodsId), "goods_id", goodsId);
//        queryWrapper.like(CharSequenceUtil.isNotEmpty(goodsName), "goods_name", goodsName);
//         trim(replace(title,' ','')) like trim(replace('%李杨 技术博客%',' ',''));
//        queryWrapper.like(CharSequenceUtil.isNotEmpty(goodsName), "trim(replace(goods_name,' ','')) "," trim(replace('%"+goodsName+"%',' ',''))");
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(eqGoodsName), "goods_name", eqGoodsName);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(storeId), "store_id", storeId);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(supplierId), "supplier_id", supplierId);
//        queryWrapper.nested(CharSequenceUtil.isNotEmpty(storeAndSupplierId), i -> i.eq("store_id", storeAndSupplierId).or().eq("supplier_id", storeAndSupplierId));
        queryWrapper.like(CharSequenceUtil.isNotEmpty(storeName), "store_name", storeName);
        if(StringUtils.isNotEmpty(categoryPath)){
                queryWrapper.and(qw -> qw
                        .like("category_path", categoryPath)
                        .or()
                        .like("category_path_son", categoryPath)
                );
        }
        queryWrapper.like(CharSequenceUtil.isNotEmpty(storeCategoryPath), "store_category_path", storeCategoryPath);
        queryWrapper.eq(selfOperated != null, "self_operated", selfOperated);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(marketEnable), "market_enable", marketEnable);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(authFlag), "auth_flag", authFlag);
        queryWrapper.le(leQuantity != null, "quantity", leQuantity);
        queryWrapper.ge(geQuantity != null, "quantity", geQuantity);
        queryWrapper.le(recommend != null, "recommend", recommend);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(goodsType), "goods_type", goodsType);
        queryWrapper.in(CollUtil.isNotEmpty(ids), "id", ids);
        queryWrapper.in(CollUtil.isNotEmpty(goodsIds), "goods_id", goodsIds);

        queryWrapper.eq(isProxyGoods != null, "is_proxy_goods", isProxyGoods);

        queryWrapper.in(supportProxy != null, "support_proxy", supportProxy);
        queryWrapper.in(supportPurchase != null, "support_purchase", supportPurchase);

        queryWrapper.eq(CharSequenceUtil.isNotEmpty(scene), "scene", scene);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(salesModel), "sales_model", salesModel);

        queryWrapper.eq("delete_flag", deleteFlag != null && deleteFlag);
        queryWrapper.eq(isGreenGoods!=null,"is_green_goods",isGreenGoods);
        if (isVipGoods != null) {
            if (isVipGoods) {
                queryWrapper.eq("is_vip_goods",isVipGoods);
            } else {
                queryWrapper.and(q -> q.eq("is_vip_goods",isVipGoods).or().isNull("is_vip_goods"));
            }
        }
        if (isCommonwealGoods != null) {
            if (isCommonwealGoods) {
                queryWrapper.eq("is_commonweal_goods",isCommonwealGoods);
            } else {
                queryWrapper.and(q -> q.eq("is_commonweal_goods",isCommonwealGoods).or().isNull("is_commonweal_goods"));
            }
        }
        //是否新品
        if (isNew != null) {
            if (isNew) {
                queryWrapper.ge("create_time", DateUtil.offsetWeek(new Date(), -1));
            }
            if (!isNew) {
                queryWrapper.le("create_time", DateUtil.offsetWeek(new Date(), -1));
            }
        }
        if (StringUtils.isNotEmpty(mhId)) {
            queryWrapper.eq("mh_id", mhId);
        }
        if (publishType != null) {
            queryWrapper.eq("publish_type", publishType);
        }
        if (goodsTag != null) {
            queryWrapper.eq("goods_tag", goodsTag);
        }

        if(notGoodsIds != null && !notGoodsIds.isEmpty()){
            queryWrapper.notIn("id",notGoodsIds);
        }

        if (goodsTagList != null) {
            queryWrapper.in("goods_tag", (Object[]) goodsTagList.split(","));
        }
        if (StringUtils.isNotEmpty(mhNotId)) {
            queryWrapper.notIn("id", (Object[]) mhNotId.split(","));
        }
        if (StringUtils.isNotEmpty(startCreateTime)) {
            queryWrapper.ge("create_time", startCreateTime);
        }
        if (StringUtils.isNotEmpty(endCreateTime)) {
            queryWrapper.le("create_time", endCreateTime);
        }
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.eq("mh_id", name);
        }
        if (isMh!= null) {
            if (isMh) {
                queryWrapper.isNotNull("mh_id");
            } else {
                queryWrapper.and(q -> q.isNull("mh_id").or().eq("mh_id",""));
                if (publishType == null) {
                    //选择大奖时，进行一下过滤
                    queryWrapper.notIn("goods_type", GoodsTypeEnum.BOX_GOODS.name(), GoodsTypeEnum.BOX_PARENT_GOODS.name(), GoodsTypeEnum.PRIZE_GOODS.name());
                }
            }
        }
        else {
            //没有传是否盲盒 && mhId为空 ： 不允许查询到盲盒商品 和 转盘抽奖商品。防止数据乱窜
            boolean boxType = !GoodsTypeEnum.BOX_GOODS.name().equals(goodsType);
            boolean boxParent = !GoodsTypeEnum.BOX_PARENT_GOODS.name().equals(goodsType);
            if (StringUtils.isEmpty(mhId) && StringUtils.isEmpty(id) && boxType && boxParent) {
                queryWrapper.notIn("goods_type", GoodsTypeEnum.BOX_GOODS.name(), GoodsTypeEnum.BOX_PARENT_GOODS.name(), GoodsTypeEnum.PRIZE_GOODS.name());
            }
        }
        if (StringUtils.isNotEmpty(extendId)) {
            queryWrapper.eq("extend_id", extendId);
        }
//        if (StringUtils.isNotEmpty(goodsName)) {
//            goodsName = "%" + goodsName.replaceAll(" ", "") + "%";
//        }
        if (StringUtils.isNotEmpty(goodsName)) {
            queryWrapper.like("replace(goods_name, ' ', '')" , goodsName.replaceAll(" ", ""));
        }
        queryWrapper.orderByDesc("create_time");
        this.betweenWrapper(queryWrapper);
        return queryWrapper;
    }

    private <T> void betweenWrapper(QueryWrapper<T> queryWrapper) {
        if (CharSequenceUtil.isNotEmpty(price)) {
            String[] s = price.split("_");
            if (s.length > 1) {
                queryWrapper.between("price", s[0], s[1]);
            } else {
                queryWrapper.ge("price", s[0]);
            }
        }
    }

    public <T> QueryWrapper<T> queryWrapperGoodsSkuByCustomSql() {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (CharSequenceUtil.isNotEmpty(id)) {
            queryWrapper.in("gs.id", Arrays.asList(id.split(",")));
        }
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(goodsId), "gs.goods_id", goodsId);
        queryWrapper.like(CharSequenceUtil.isNotEmpty(goodsName), "gs.goods_name", goodsName);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(storeId), "gs.store_id", storeId);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(supplierId), "gs.supplier_id", supplierId);
        queryWrapper.nested(CharSequenceUtil.isNotEmpty(storeAndSupplierId), i -> i.eq("gs.store_id", storeAndSupplierId).or().eq("gs.supplier_id", storeAndSupplierId));
        queryWrapper.like(CharSequenceUtil.isNotEmpty(storeName), "gs.store_name", storeName);
        queryWrapper.like(CharSequenceUtil.isNotEmpty(categoryPath), "gs.category_path", categoryPath);
        queryWrapper.like(CharSequenceUtil.isNotEmpty(storeCategoryPath), "gs.store_category_path", storeCategoryPath);
        queryWrapper.eq(selfOperated != null, "gs.self_operated", selfOperated);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(marketEnable), "gs.market_enable", marketEnable);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(authFlag), "gs.auth_flag", authFlag);
        queryWrapper.le(leQuantity != null, "gs.quantity", leQuantity);
        queryWrapper.ge(geQuantity != null, "gs.quantity", geQuantity);
        queryWrapper.le(recommend != null, "gs.recommend", recommend);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(goodsType), "gs.goods_type", goodsType);
        queryWrapper.in(CollUtil.isNotEmpty(ids), "gs.id", ids);
        queryWrapper.in(CollUtil.isNotEmpty(goodsIds), "gs.goods_id", goodsIds);


        queryWrapper.eq(isProxyGoods != null, "gs.is_proxy_goods", isProxyGoods);

        queryWrapper.in(supportProxy != null, "gs.support_proxy", supportProxy);
        queryWrapper.in(supportPurchase != null, "gs.support_purchase", supportPurchase);

        queryWrapper.eq(CharSequenceUtil.isNotEmpty(scene), "gs.scene", scene);
        queryWrapper.eq(CharSequenceUtil.isNotEmpty(salesModel), "gs.sales_model", salesModel);

        queryWrapper.eq("gs.delete_flag", false);
        return queryWrapper;
    }


}
